import { StorageConfig, PROJECT_CONFIG } from './baseStorageService';
import { investPlanService } from '../investPlanService';
import { stockPlanService } from '../stockPlanService';
import { userSettingsService } from '../userSettingsService';

// 存储管理器 - 统一管理所有业务存储服务
export class StorageManager {
  private static instance: StorageManager;
  
  // 所有业务服务的注册表
  private services = {
    investmentPlans: investPlanService,
    stockPlans: stockPlanService,
    userSettings: userSettingsService,
    // 后续可以继续添加新的业务服务
  };

  private constructor() {}

  // 单例模式
  static getInstance(): StorageManager {
    if (!StorageManager.instance) {
      StorageManager.instance = new StorageManager();
    }
    return StorageManager.instance;
  }

  // 获取所有业务服务
  getServices() {
    return this.services;
  }

  // 切换所有服务的存储方案
  async switchAllStorage(newConfig: StorageConfig): Promise<void> {
    const errors: string[] = [];
    
    for (const [serviceName, service] of Object.entries(this.services)) {
      try {
        await service.switchStorage(newConfig);
        console.log(`✅ ${serviceName} 存储切换成功`);
      } catch (error) {
        const errorMsg = `❌ ${serviceName} 存储切换失败: ${error}`;
        console.error(errorMsg);
        errors.push(errorMsg);
      }
    }
    
    if (errors.length > 0) {
      throw new Error(`部分服务存储切换失败:\n${errors.join('\n')}`);
    }
    
    // 更新用户设置中的存储配置
    await userSettingsService.updateStorageConfig(newConfig);
  }

  // 导出所有业务数据
  async exportAllData(): Promise<{ [serviceName: string]: string }> {
    const exportData: { [serviceName: string]: string } = {};
    
    for (const [serviceName, service] of Object.entries(this.services)) {
      try {
        exportData[serviceName] = await service.exportAll();
      } catch (error) {
        console.error(`导出 ${serviceName} 数据失败:`, error);
        exportData[serviceName] = '[]'; // 空数据
      }
    }
    
    return exportData;
  }

  // 导入所有业务数据
  async importAllData(data: { [serviceName: string]: string }): Promise<void> {
    const errors: string[] = [];
    
    for (const [serviceName, jsonData] of Object.entries(data)) {
      if (this.services[serviceName as keyof typeof this.services]) {
        try {
          await this.services[serviceName as keyof typeof this.services].import(jsonData);
          console.log(`✅ ${serviceName} 数据导入成功`);
        } catch (error) {
          const errorMsg = `❌ ${serviceName} 数据导入失败: ${error}`;
          console.error(errorMsg);
          errors.push(errorMsg);
        }
      }
    }
    
    if (errors.length > 0) {
      throw new Error(`部分数据导入失败:\n${errors.join('\n')}`);
    }
  }

  // 清空所有业务数据
  async clearAllData(): Promise<void> {
    const errors: string[] = [];
    
    for (const [serviceName, service] of Object.entries(this.services)) {
      try {
        await service.clear();
        console.log(`✅ ${serviceName} 数据清空成功`);
      } catch (error) {
        const errorMsg = `❌ ${serviceName} 数据清空失败: ${error}`;
        console.error(errorMsg);
        errors.push(errorMsg);
      }
    }
    
    if (errors.length > 0) {
      throw new Error(`部分数据清空失败:\n${errors.join('\n')}`);
    }
  }

  // 获取所有业务数据统计
  async getDataStatistics(): Promise<{
    [serviceName: string]: {
      count: number;
      storeName: string;
      storageType: string;
    }
  }> {
    const statistics: {
      [serviceName: string]: {
        count: number;
        storeName: string;
        storageType: string;
      }
    } = {};
    
    for (const [serviceName, service] of Object.entries(this.services)) {
      try {
        const data = await service.getAll();
        const config = service.getStorageConfig();
        
        statistics[serviceName] = {
          count: data.length,
          storeName: service.getStoreName(),
          storageType: config.type
        };
      } catch (error) {
        console.error(`获取 ${serviceName} 统计失败:`, error);
        statistics[serviceName] = {
          count: 0,
          storeName: 'unknown',
          storageType: 'unknown'
        };
      }
    }
    
    return statistics;
  }

  // 检查存储健康状态
  async checkStorageHealth(): Promise<{
    [serviceName: string]: {
      status: 'healthy' | 'error';
      message: string;
    }
  }> {
    const healthStatus: {
      [serviceName: string]: {
        status: 'healthy' | 'error';
        message: string;
      }
    } = {};
    
    for (const [serviceName, service] of Object.entries(this.services)) {
      try {
        // 尝试读取数据来检查存储是否正常
        await service.getAll();
        healthStatus[serviceName] = {
          status: 'healthy',
          message: '存储正常'
        };
      } catch (error) {
        healthStatus[serviceName] = {
          status: 'error',
          message: `存储异常: ${error}`
        };
      }
    }
    
    return healthStatus;
  }

  // 获取项目配置信息
  getProjectConfig() {
    return PROJECT_CONFIG;
  }

  // 注册新的业务服务
  registerService<T extends { id: string }>(
    name: string, 
    service: { 
      getAll(): Promise<T[]>;
      exportAll(): Promise<string>;
      import(data: string): Promise<void>;
      clear(): Promise<void>;
      switchStorage(config: StorageConfig): Promise<void>;
      getStorageConfig(): StorageConfig;
      getStoreName(): string;
    }
  ): void {
    (this.services as any)[name] = service;
  }
}

// 导出单例实例
export const storageManager = StorageManager.getInstance();